package win.larryzeal.c01.realm;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shiro.realm.jdbc.JdbcRealm;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * Created by 张少昆 on 2017/11/18.
 */
public class MyJdbcRealm extends JdbcRealm {
    public MyJdbcRealm(){
        super.setDataSource(dataSource());
        super.setAuthenticationQuery("select password from users where username = ?");//用的是默认的
        super.setPermissionsQuery("select permission from roles_permissions where role_name = ?");
        super.setUserRolesQuery("select role_name from user_roles where username = ?");
        super.setPermissionsLookupEnabled(false); //默认就是false，如果true，需要设置权限解析器、角色权限解析器吧。
        //org.apache.shiro.realm.AuthorizingRealm.AuthorizingRealm(org.apache.shiro.cache.CacheManager, org.apache.shiro.authc.credential
        //上面，在构造对象的时候默认就设置了WildcardPermissionResolver！
    }

    /**
     * 最简单的DruidDataSource对象
     *
     * @return
     */
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/shiro");
        dataSource.setUsername("root");
        dataSource.setPassword("root@localhost");
        try{
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.init();
        } catch(SQLException e){
            e.printStackTrace();
        }
        return dataSource;
    }
}
